package com.example.wc.logindemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.example.wc.logindemo.blogdb.BlogBaseHelper;
import com.example.wc.logindemo.blogdb.BlogCursorWrapper;
import com.example.wc.logindemo.blogdb.BlogDbSchema.BlogTable;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.wc.logindemo.DateByDate.*;

/**
 * Created by hui on 2017/2/17.
 * 单例，mBlogs为get博客文章列表
 */

public class BlogLab {
    private static BlogLab sBlogLab;

    private Context mContext;
    private SQLiteDatabase mDatabase;

//    private List<Blog> mBlogs;

    public static BlogLab get(Context context){
        if(sBlogLab == null) {
            sBlogLab = new BlogLab(context);
        }
        return sBlogLab;
    }

    private BlogLab(Context context){
        mContext = context.getApplicationContext();
        mDatabase = new BlogBaseHelper(mContext).getWritableDatabase();

//        mBlogs = new ArrayList<>();
//        for(int i = 0; i < 20; i++){
//            mBlog.add(new Blog("标题" + i, "举头望明月，低头思故乡。举头望明月，低头思故乡。举头望明月，低头思故乡。举头望明月，低头思故乡。" + i));
//        }

    };

    //与网络请求get的信息类型一致
    public static  class Content{
        List<Blog> content;
    }

    public void addBlog(Blog b){
        ContentValues values = getContentValues(b);

        mDatabase.insert(BlogTable.NAME, null, values);
    }

//    public void deleteBlogByDate(Blog b){
//        String dateString = b.getDate().toString();
    public void deleteBlogOne(String dateString){
        mDatabase.delete(BlogTable.NAME, BlogTable.Cols.DATE + " = ?", new String[]{ dateString });
    }

//    public void deleteBlogByDate(Date date){
//        String dateString = date.toString();
    public void delete(Blog blog){

    }

    public void deleteBlogByDate(long date){
        mDatabase.delete(BlogTable.NAME, BlogTable.Cols.DATE + " = ?", new String[]{String.valueOf(date)});
    }
    public void deleteBlogById(String id){
        mDatabase.delete(BlogTable.NAME, BlogTable.Cols.ID + " = ?", new String[]{ id });
    }

    //如果size>1，保留最后一行数据，删除其他数据
    public void deleteBlogSaveLast(String id){
        if(getSameIdBlogs(id).size()!=1){
            List<Blog> blogs = getSameIdBlogs(id);
            long last = getSameIdBlogs(id).get(getSameIdBlogs(id).size()-1).getDate().getTime();
            mDatabase.delete(BlogTable.NAME, BlogTable.Cols.ID + " = ?"
                    + " and " + BlogTable.Cols.DATE + " < ?", new String[]{ id,""+last});
//            mDatabase.delete(BlogTable.NAME, "id = ? and date < ?", new String[]{ id,""+last});
        }
    }


    public void deleteBlogByDate(String id) throws ParseException {
        if(getSameIdBlogs(id).size() != 1){//getSameIdBlogs(id)在service已做判断不为null
            List<Blog> blogs = getSameIdBlogs(id);
            for(int j = 0; j<getSameIdBlogs(id).size(); j++){
                Date date = blogs.get(j).getDate();
                long time = date.getTime();//保存当天
                long timeZero = DayByDate(date);//保存当天00:00date
                long timeNowZero = DayByDate(new Date());//当前当天00:00date
                long between = timeNowZero-timeZero;
                long timeBegin =BeginByDate(date);//保存当天那个小时开始的整点
                long betweenHour = time - timeBegin;

                if(between > (90*24*60*60*1000l)){
//                if(between > (20*60*1000l)){
                    mDatabase.delete(BlogTable.NAME, BlogTable.Cols.ID + " = ?" + " and "
                            + BlogTable.Cols.DATE + " <= ?", new String[]{ id, String.valueOf(time)});
                }
                else if(between > 24*60*60*1000l && between <= 90*24*60*60*1000l){
//                else if(between > 5*60*1000l && between <= 20*60*1000l){
                    mDatabase.delete(BlogTable.NAME, BlogTable.Cols.ID + " = ?" + " and "
                            + BlogTable.Cols.DATE + " >= ?" + " and "
                            + BlogTable.Cols.DATE + " < ?",
                            new String[]{ id, String.valueOf(timeZero), String.valueOf(time)});
                }
                else if(betweenHour > 60*60*1000l && between < 24*60*60*1000l){
//                else if(betweenHour > 1000l && between <= 5*60*1000l){
                    BlogCursorWrapper cursor =queryBlogs(BlogTable.Cols.ID + " = ?" + " and "
                                    + BlogTable.Cols.DATE + " >= ?" + " and "
                                    + BlogTable.Cols.DATE + " <= ?",
                            new String[]{ id, String.valueOf(timeBegin),String.valueOf(time)});
                    if(cursor.getCount()> 1){
                        cursor.moveToFirst();
                        while (!cursor.isAfterLast()){
                            deleteBlogByDate(cursor.getBlog().getDate().getTime());
                            cursor.moveToNext();
                        }
                    }
                    cursor.close();
                }
            }
//            long last = getSameIdBlogs(id).get(getSameIdBlogs(id).size()-1).getDate().getTime();
//            mDatabase.delete(BlogTable.NAME, BlogTable.Cols.ID + " = ?"
//                    + " and " + BlogTable.Cols.DATE + " < ?", new String[]{ id,""+last});
//            mDatabase.delete(BlogTable.NAME, "id = ? and date < ?", new String[]{ id,""+last});
        }
    }

    //查找不重复的Id并返回List
    public List<String> getBlogsId() {
        List<String> blogsId = new ArrayList<>();
        //用于消除重复记录的 DISTINCT 关键字
        BlogCursorWrapper cursor = queryBlogsByColumns(new String[]{"DISTINCT id"}, null, null);

        try{
            cursor.moveToFirst();
            while (!cursor.isAfterLast()){
                blogsId.add(cursor.getId());//新增BlogCursorWrapper.getId()方法
                cursor.moveToNext();
            }
        }finally {
            cursor.close();
        }

        return blogsId;
    }

    public List<Blog> getBlogs() {
//        return mBlogs;
        List<Blog> blogs =  new ArrayList<>();
        BlogCursorWrapper cursor = queryBlogs(null, null);

        try{
            cursor.moveToFirst();
            while (!cursor.isAfterLast()){
                blogs.add(cursor.getBlog());
                cursor.moveToNext();
            }
        }finally {
            cursor.close();
        }

        return blogs;
    }

    public List<Blog> getSameIdBlogs(String id) {
        List<Blog> blogs =  new ArrayList<>();
        BlogCursorWrapper cursor = queryBlogs(
                BlogTable.Cols.ID + " = ?",
                new String[]{ id }
        );

        try{
            cursor.moveToFirst();
            while (!cursor.isAfterLast()){
                blogs.add(cursor.getBlog());
                cursor.moveToNext();
            }
        }finally {
            cursor.close();
        }

        return blogs;
    }

    public Blog getBlog(String id){
        BlogCursorWrapper cursor = queryBlogs(
                BlogTable.Cols.ID + " = ?",
                new String[]{ id }
        );

        try{
            if(cursor.getCount() == 0){
                return null;
            }

            cursor.moveToFirst();
            return cursor.getBlog();
        }finally {
            cursor.close();
        }
    }

    public File getPhotoFile(Blog blog){
        File externalFilesDir = Environment.getExternalStorageDirectory(); //mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        if(externalFilesDir == null){
            return null;
        }

        return new File(externalFilesDir, blog.getPhotoFilename());
    }

    public File getPhotoCropFile(Blog blog){
        File externalFilesDir = Environment.getExternalStorageDirectory(); //mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        if(externalFilesDir == null){
            return null;
        }

        return new File(externalFilesDir, blog.getPhotoCropFilename());
    }

    public void updateBlog(Blog blog){
        String id = blog.getId();
        ContentValues values = getContentValues(blog);

        mDatabase.update(BlogTable.NAME, values,
                BlogTable.Cols.ID + " = ?",
                new String[]{ id });
    }

    private static ContentValues getContentValues(Blog blog){
        ContentValues values = new ContentValues();
        values.put(BlogTable.Cols.ID, blog.getId());
        values.put(BlogTable.Cols.NAME, blog.getName());
        values.put(BlogTable.Cols.CONTENT, blog.getContent());
        values.put(BlogTable.Cols.DATE, blog.getDate().getTime());

        return values;
    }

    private BlogCursorWrapper queryBlogs(String whereClause, String[] whereArgs){
        Cursor cursor = mDatabase.query(
                BlogTable.NAME,
                null,
                whereClause,
                whereArgs,
                null,
                null,
                null
        );
        return new BlogCursorWrapper(cursor);
    }
    //String[] columns：要查询出来的列名。相当于select语句select关键字后面的部分。
    private BlogCursorWrapper queryBlogsByColumns(String[] columns, String whereClause, String[] whereArgs){
        Cursor cursor = mDatabase.query(
                BlogTable.NAME,
                columns,
                whereClause,
                whereArgs,
                null,
                null,
                null
        );
        return new BlogCursorWrapper(cursor);
    }
}
